#include "LoginWidget.h"
#include "ui_LoginWidget.h"
#include"HomeWidget.h"
#include"RegisterWidget.h"
#include"HttpManage.h"
#include"Global.h"
#include<QFile>
#include<QKeyEvent>
#include<QDebug>
#include<QDesktopServices>
#include<memory>
#include<QStyleOption>
#include<QBitmap>
#include<QPainter>
#include<QJsonObject>
#include<QMessageBox>
LoginWidget::LoginWidget(QWidget *parent)
    : QLabel(parent)
    , ui(new Ui::LoginWidget)
{
    ui->setupUi(this);
    SetStyleInit();
    //关闭按钮
    connect(ui->CloseButton,&QPushButton::clicked,this,[this](){this->close();});

    //默认情况下登录按钮不可用
    ui->LoginPushButton->setEnabled(false);
    //连接信号与槽
    connect(ui->UsernameLineEdit,&QLineEdit::textChanged,this,&LoginWidget::CheckInputs);
    connect(ui->PasswordLineEdit,&QLineEdit::textChanged,this,&LoginWidget::CheckInputs);
    connect(ui->ImpowerCheckBox,&QCheckBox::stateChanged,this,&LoginWidget::CheckInputs);
    // 连接 Token 过期信号
    connect(HttpManage::GetInstance().get(), &HttpManage::sig_token_expired,this, &LoginWidget::handle_token_expired);
    initHttpHandlers();
    //连接登录回包信号
    connect(HttpManage::GetInstance().get(),&HttpManage::sig_login_mod_finish,this,&LoginWidget::slot_login_mod_finish);
}

LoginWidget::~LoginWidget()
{
    delete ui;
}
void LoginWidget::paintEvent(QPaintEvent *event)
{
    //绘制样式
    QStyleOption opt;
    opt.initFrom(this);
    QPainter p(this);
    style()->drawPrimitive(QStyle::PE_Widget, &opt, &p, this);//绘制样式

    QBitmap bmp(this->size());
    bmp.fill();
    QPainter painter(&bmp);

    painter.setPen(Qt::NoPen);
    painter.setBrush(Qt::black);
    painter.setRenderHint(QPainter::Antialiasing);
    //设置边框为圆角12px
    painter.drawRoundedRect(bmp.rect(), 8, 8);
    setMask(bmp);
    QWidget::paintEvent(event);
}
bool LoginWidget::checkPwdValid()
{
    return true;
}

void LoginWidget::initHttpHandlers()
{
    //获取登录回包逻辑
    _handles.insert(ReqId::ID_LOGIN_USER,[this](QJsonObject jsonObj){
       int error = jsonObj["error"].toInt();
       ui->LoginPushButton->setEnabled(true);
       if(error != ErrorCode::SUCCESS)
       {
           QString errorMessage;
           switch (error)
           {
               case ErrorCode::PasswdInvalid:
                    errorMessage = "用户名密码不匹配";
                    break;
               default:
                    errorMessage = QString("未知错误 (代码: %1)").arg(error);
           }
           QMessageBox::warning(this, "登录失败", errorMessage);
               return;
       }

       // 解析并存储认证信息
       QJsonObject authInfo = jsonObj;
       QString token = authInfo["token"].toString();
       QString uid = authInfo["uid"].toString();
       QString user = authInfo["user"].toString();


       // 存储到 HTTP 管理模块
       HttpManage::GetInstance()->SetAuthInfo(token, uid,user);
       qDebug()<<"user:"<<user<<"uid:"<<uid<<"token"<<token<<'\n';
       // 关闭登录窗口（根据业务需求可选）
       this->close();

       // 提示登录成功
       QMessageBox::information(this, "欢迎回来",
       QString("欢迎 %1").arg(ui->UsernameLineEdit->text()));
       HomeWidget* home = new HomeWidget();
        home->show();
    });
}
void LoginWidget::SetStyleInit()
{
//    //设置圆角边框
//    QPainterPath PainterPath;	//绘制一个QPainter路径对象
//    PainterPath.addRoundedRect(this->rect(), 8, 8);	//对它设置路径为四周圆角。8即圆角的深度，可以修改
//    QRegion mask = QRegion(PainterPath.toFillPolygon().toPolygon());	//创建遮罩对象，内容即该QPainter路径
//    this->setMask(mask);	//为QWidget覆盖上这个遮罩

    //设置窗口图标
    QIcon icon(":/assets/cloud_red.png");
    this->setWindowIcon(icon);
    //隐藏窗口边框
    this->setWindowFlags(Qt::FramelessWindowHint);
    //给当前对象安装事件筛选器
    this->installEventFilter(this);
    //设置初始头像
    ui->ProfileLabel->setPixmap(QPixmap(":/assets/cloud_gold.png").scaled((ui->ProfileLabel->size()),Qt::IgnoreAspectRatio,Qt::SmoothTransformation));
    //设置qss样式
    QFile file(":/assets/LoginWidget.qss");
    if(file.open(QFile::OpenModeFlag::ReadOnly))
    {
        this->setStyleSheet(file.readAll());
        file.close();
    }
    else
    {
        qDebug("read qss failed\n");
    }
}
void LoginWidget::keyPressEvent(QKeyEvent *ev)
{
    if(ev->key() == Qt::Key_F5)
    {
        qDebug()<<"刷新\n";
        QFile file("D:/qt_code/Login/assets/LoginWidget.qss");
        if(file.open(QFile::OpenModeFlag::ReadOnly))
        {
            this->setStyleSheet(file.readAll());
        }
    }
    return QLabel::keyPressEvent(ev);
}

bool LoginWidget::eventFilter(QObject *obj, QEvent *ev)
{
    if(obj == this)
    {
        QMouseEvent* MouseEvent = dynamic_cast<QMouseEvent*>(ev);
        if(MouseEvent != nullptr)
        {
            static QPoint Offset;
            if(MouseEvent->type() == QEvent::Type::MouseButtonPress)
            {
                //计算偏移量
                Offset = MouseEvent->globalPos() - this->pos();
            }
            else if(MouseEvent->type() == QEvent::Type::MouseMove)
            {
                this->move(MouseEvent->globalPos() - Offset);
            }
        }
    }
    return QLabel::eventFilter(obj,ev);
}

void LoginWidget::CheckInputs()
{
    int is_true = false;
    is_true = !ui->UsernameLineEdit->text().isEmpty() && !ui->PasswordLineEdit->text().isEmpty() && ui->ImpowerCheckBox->isChecked();
    ui->LoginPushButton->setEnabled(is_true);
}

void LoginWidget::on_AgreementPushButton_clicked()
{
    QDesktopServices::openUrl(QUrl(QLatin1String("https://www.julyedu.com/agreement/priv")));
}

void LoginWidget::on_HidePushButton_clicked()
{
    this->showMinimized();
}

void LoginWidget::on_LoginPushButton_clicked()
{
    //_home.show();
    ui->LoginPushButton->setEnabled(false);
    QString userName = ui->UsernameLineEdit->text();
    QString pwd = ui->PasswordLineEdit->text();

    //发送http请求登录
    QJsonObject json_obj;
    json_obj["userName"] = userName;
    json_obj["pwd"] = md5Encrypt(pwd);
    HttpManage::GetInstance()->PostHttpReq(QUrl(gate_url_prefix+"/user_login"),json_obj,ReqId::ID_LOGIN_USER,Modules::LOGINMOD);
}

void LoginWidget::on_RegisterPushButton_clicked()
{
    //this->hide();
    //RegisterWidget* registerWidget = new RegisterWidget(this);
    //registerWidget->show();
    RegisterWidget* reg = new RegisterWidget();
    reg->show();
}

void LoginWidget::on_RetrievePushButton_clicked()
{
    GetBack* getBack = new GetBack();
    getBack->show();
}

void LoginWidget::slot_login_mod_finish(ReqId id, QString res,ErrorCode err)
{
    if(err != ErrorCode::SUCCESS)
    {
        qDebug()<<"网络请求错误";
        ui->LoginPushButton->setEnabled(true);
        QMessageBox::warning(this, "网络请求错误", "服务器未响应");
        return;
    }
    //解析json字符串，res需要转化为QByteArray
    QJsonDocument jsonDoc = QJsonDocument::fromJson(res.toUtf8());
    //json解析错误
    if(jsonDoc.isNull())
    {
        qDebug()<<"json解析错误";
        return ;
    }
    if(!jsonDoc.isObject())
    {
        qDebug()<<"json解析错误";
        return;
    }
    //调用对应的逻辑，按照id回调
    _handles[id](jsonDoc.object());
    return;
}

void LoginWidget::handle_token_expired()
{
      QMessageBox::information(this, "会话过期", "登录已失效，请重新登录");
      ui->PasswordLineEdit->clear(); // 清空密码
      show(); // 显示登录窗口
}
